<?php
defined('G_IN_SYSTEM')or exit('No permission resources.');
System::load_app_class('base','mobileapi','no');
System::load_app_fun("pay","pay");
class cart extends base {
	private $Cartlist;
	private $member;
	public function __construct() {
		parent::__construct();
		$this->db = System::load_sys_class("model");

	}
	public function getUserInfo($uid){
		$member=$this->db->GetOne("select * from `@#_member` where `uid`='$uid'");
		return $member;
	}
	//根据购物车的商品id获取商品列表
	public function getShoplist($sids)
	{
    	foreach ($sids as $key => $value) {
    			$shopids.=intval($value["shopid"]).',';
    	}
    	$shopids=str_replace(',0','',$shopids);
    	$shopids=trim($shopids,',');
		$shoplist=$this->db->GetList("SELECT * FROM `@#_shoplist` where `id` in($shopids) and `q_uid` is null ",array("key"=>"id"));
		return $shoplist;
	}
	//购物车商品列表
	public function cartlist(){

		//$Mcartlist=json_decode(stripslashes($this->Cartlist),true);
		$Mcartlist=json_decode(stripslashes($_POST['cartlist']),true);

		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');

		}
		//echo $shopids;
		$shoplist=array();
		if($shopids!=NULL){
			$shoparr=$this->db->GetList("SELECT * FROM `@#_shoplist` where `id` in($shopids)",array("key"=>"id"));
		}
		if(!empty($shoparr)){
		  foreach($shoparr as $key=>$val){
		    if($val['q_end_time']=='' || $val['q_end_time']==NULL){
			   $shoplist[$key]=$val;
			   $Mcartlist[$val['id']]['num']=$Mcartlist[$val['id']]['num'];
			   $Mcartlist[$val['id']]['shenyu']=$val['shenyurenshu'];
			   $Mcartlist[$val['id']]['money']=$val['yunjiage']* $Mcartlist[$val['id']]['num'];

			}
		  }
		  _setcookie('Cartlist',json_encode($Mcartlist),'');
		}

		$MoenyCount=0;
		$Cartshopinfo='{';
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
					$key=intval($key);
					if(isset($shoplist[$key])){
						$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
						$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
						$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
						$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
						$Cartshopinfo.="'$key':{'shenyu':".$shoplist[$key]['cart_shenyu'].",'num':".$val['num'].",'money':".$shoplist[$key]['yunjiage']."},";
					}
			}
		}

		$shop=0;

		if(!empty($shoplist)){
		   $shop=1;
		}

		$MoenyCount=substr(sprintf("%.3f",$MoenyCount),0,-1);
		var_dump($MoenyCount);exit();

	}


    public function local_cartlist() {
        $shopids = $_POST['shopids'];
        if($shopids!=NULL){
            $shoparr=$this->db->GetList("SELECT `cateid`,`id`,`zongrenshu`,`shenyurenshu`,`businessid`,`thumb`,`priceStep`,`title`,`qishu`,`sid` FROM @#_shoplist where `id` in (SELECT max(id)as id FROM qy_shoplist where `sid` in ($shopids) group by`sid`) AND `state`=1 ");
            $cateids = '';
            foreach($shoparr as $key => $value){
                $bunissid = $value['businessid'];
                $result = $this->db->GetOne("SELECT * FROM `@#_business` WHERE `id` = $bunissid");
                $businesslogo = $result['businesslogo'];
                $businessname = $result['name'];
                $shoparr[$key]['businesslogo'] = $businesslogo;
                $shoparr[$key]['shopnames'] = $businessname;
                $cateids.=$value['cateid'].',';
            }
            $cateids = trim($cateids,',');
            $parentid = $this->db->GetList("SELECT `parentid` FROM `@#_category` WHERE `cateid` IN ($cateids)");
            $pid = $parentid[0]['parentid'];
            $cates = $this->db->GetList("SELECT `cateid` FROM `@#_category` WHERE `parentid` = $pid");
            $cateids = '';
            foreach($cates as $key => $value){
                $cateids.=$value['cateid'] . ',';
            }
            $cateids = trim($cateids,',');
//			$this->success($cateids);
            $guessLikeArr = $this->db->GetList("SELECT `thumb`,`sid` FROM `@#_shoplist` WHERE `cateid` in ($cateids) AND `sid` NOT IN ($shopids)AND `state`=1 AND `id` >= ((SELECT max(`id`) FROM `@#_shoplist`) - (SELECT MIN(`id`) FROM `@#_shoplist`)) * RAND() + (SELECT MIN(`id`) FROM `@#_shoplist`) GROUP BY `sid`LIMIT 10");

        }
        $sids = $shopids.',';
        foreach($guessLikeArr as $key => $value){
            $sids .= $value['sid'] . ',';
        }
        $sids = trim($sids,',');
        if(count($guessLikeArr) < 10){
            $limit = 10 - count($guessLikeArr);
            if($sids){
                $seleter = "AND `sid` NOT IN ($sids)";
            }
            $temp = $this->db->GetList("SELECT `thumb`,`sid` FROM `@#_shoplist` WHERE `state`=1 $seleter GROUP BY `sid` ORDER BY `renqi` limit $limit");
            if(!$guessLikeArr){
                $guessLikeArr = $temp;
            }else {
                $guessLikeArr = array_merge($guessLikeArr, $temp);
            }
        }
        if($shoparr) {
            $this->success(array('cartInfo'=>$shoparr,'guessLike'=>$guessLikeArr));
        }
        else{
            $this->success(array('error'=>'购物车为空','guessLike'=>$guessLikeArr));
        }
    }
	

public function webhook(){
	$appId = "2699b26c-81f3-41ba-a84e-471ca62d7b39";
    $appSecret = "69234baa-a524-433b-aebc-bbf3d24eeea8";//(live Mode)
    $jsonStr = file_get_contents("php://input");

$this->db->Query("INSERT INTO `@#_webhock_log` (`content`) VALUE ('$jsonStr')");
//测试数据
$msg = json_decode($jsonStr);

// webhook字段文档: https://beecloud.cn/doc/?index=webhook

//第一步:验证签名
$sign = md5($appId . $appSecret . $msg->timestamp);
if ($sign != $msg->sign) {
    // 签名不正确
    $this->failed('签名不正确');
}


//第二步:过滤重复的Webhook
//客户需要根据订单号进行判断是否已经付款，忽略已经处理过的订单号对应的Webhook
$uid=$msg->optional->uid;

$code=$msg->transaction_id;

if (strpos($code, 'C1')===0) {
	$ifOrder=$this->db->GetList("SELECT `id` FROM `@#_member_addmoney_record` where `status` like '%已付款%' and `code`='$code'");
	$totalAmount=$this->db->GetOne("select money from `@#_member_addmoney_record` where `code` = '$code' and `uid` ='$uid' and `status` like '%未付款%'");
	$MoneyCount=$totalAmount['money'] * 100;
}
if (strpos($code, 'A1')===0) {
$ifOrder=$this->db->GetList("SELECT `id` FROM `@#_member_go_record` where `status` like '%已付款%' and `code`='$code'");
$totalAmount = $this->db->GetOne("select sum(moneycount) as totalAmount from `@#_member_go_record` where `code` = '$code' and `uid` ='$uid'");
$MoneyCount=$totalAmount['totalAmount'] * 100;

}

if($ifOrder){
  exit('该订单已经付款');
}

//第三步:验证订单金额与购买的产品实际金额是否一致
//也就是验证调用Webhook返回的transaction_fee订单金额是否与客户服务端内部的数据库查询得到对应的产品的金额是否相同

if($msg->transaction_fee !=$MoneyCount){
  exit('金额不对');
}

//第四步:处理业务逻辑和返回
if($msg->transaction_type == "PAY") { //支付的结果
    //付款信息
    //支付状态是否变为支付成功,true代表成功
    $result = $msg->trade_success;
    //message_detail 参考文档
    if ($result) {
     if (strpos($code, 'A1')===0) {
		 $time = time();
		 $this->db->Query("UPDATE `@#_member_go_record` SET `feedBack` = 1 WHERE `code` = '$code'");
		 $MoneyCount=$MoneyCount/100;
		 $this->db->Query("UPDATE `@#_member` SET `money` = `money` + $MoneyCount where (`uid` = '$uid')");
		 $this->db->Query("INSERT INTO `@#_member_account`(`uid`,`type`,`pay`,`content`,`money`,`time`) VALUES ('$uid', '1', '账户', '手机App充值', '$MoneyCount', '$time')");
//		 $this->db->Query("INSERT INTO `@#_member_addmoney_record`(`uid`,`code`,`money`,`pay_tpey`,`status`,`time`,`score`,`feedBack`) VALUES ('$uid','$code','$MoneyCount','手机App购买商品充值','已付款','$time',0,1)");
    	$this->payAfter($code,$uid,$MoneyCount);
	 }

	if (strpos($code, 'C1')===0) {
		$time=time();
		$money = $MoneyCount / 100;
		$query = $this->db->Query("UPDATE `@#_member_addmoney_record` SET `pay_type`='手机App充值',`status`='已付款',`feedBack`=1 WHERE `code`='$code'");
		$up_q2 = $this->db->Query("UPDATE `@#_member` SET `money` = `money` + $money where (`uid` = '$uid')");
		$up_q3 = $this->db->Query("INSERT INTO `@#_member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('$uid', '1', '账户', '手机App充值', '$money', '$time')");
		if($query && $up_q2 && $up_q3){

			echo 'success';

		}
	}


    }else{exit('支付失败');}

   /* switch ($msg->channel_type) {
        case "WX":
            
            break;
        case "ALI":
            break;
        case "UN":
            break;
        case "KUAIQIAN":
            break;
        case "JD":
            break;
        case "BD":
            break;
        case "YEE":
            break;
        case "PAYPAL":
            break;
    }*/
} else if ($msg->transaction_type == "REFUND") { //退款的结果

}


}

public function getDingdanCode(){
	$uid=$_POST['uid'];
	//$uid=5;
	$Mcartlist=$_POST['Mcartlist'];
	$member=$this->getUserInfo($uid);
	if (!$member) {
		$this->failed("无用户信息");
	}
/*$Mcartlist=Array
(	 

  5=> Array
        (
            "num" => 14,
            "money" => 14	
        ),
   8=> Array
        (
            "num" => 27,
            "money" => 27
        )
);*/
	if ($Mcartlist) {
//		$goods_count_num=0;
		$MoneyCount=0;
		$shopids='';
		foreach($Mcartlist as $key => $val){
			$shopids.=intval($key).',';
//			$goods_count_num+=$val['num'];
//			$MoneyCount+=$val['money'];
		}
		$shopids=str_replace(',0','',$shopids);
		$shopids=trim($shopids,',');
	}
	if($shopids!=NULL){
		$shoplist_temp=$this->db->GetList("SELECT * FROM `@#_shoplist` where `sid` in($shopids) and `q_uid` is null ORDER BY `id` DESC");
		for($i = 0; $i < count($shoplist_temp); $i++){
			$value = $shoplist_temp[$i];
			$key = intval($value['sid']);
			$shoplist[$key] = $value;
		}
		if($_POST['inCart']){//清空购物车
			$this->db->Query("DELETE FROM `@#_cart` WHERE `uid`= $uid");
		}
	}

	if(count($shoplist)>1){
			$dingdancode_tmp = 1;	//多个商品相同订单
	}else{
			$dingdancode_tmp = 0;	//单独商品订单
	}
	//第三方支付购买商品获取订单号
	if ($Mcartlist) {
		$dingdancode=pay_get_dingdan_code('A');
		$ip =$_POST['location'] ? $_POST['location'].','._get_ip() : _get_ip_dizhi();
		$time = time();
       foreach($Mcartlist as $key => $value){
				$key=intval($key);
				if(isset($shoplist[$key])){
				$shoplist[$key]['cart_gorenci']=$value['num'] ? $value['num'] : 1;
				$status='未付款,未发货,未完成';
				$title=$shoplist[$key]['title'];
				$qishu=$shoplist[$key]['qishu'];
				$money = $shoplist[$key]['priceStep'] * $value['num'];
				$id=$shoplist[$key]['id'];
				$username=$member['username'];
				$memberImg=$member['img'];
				$MoneyCount+=$shoplist[$key]['priceStep'] * $value['num'];
				if($value['num']){
					$insert_html.="('$dingdancode','$dingdancode_tmp','$uid','$username','$memberImg','$id','$title','$qishu','$value[num]','$money','','','$ip','$status','$time'),";
				}
			}
		}
		$sql="INSERT INTO `@#_member_go_record` (`code`,`code_tmp`,`uid`,`username`,`uphoto`,`shopid`,`shopnames`,`shopqishu`,`gonumber`,`moneycount`,`goucode`,`pay_type`,`ip`,`status`,`time`) VALUES ";
		$sql.=trim($insert_html,',');
		$this->db->Query($sql);
		$result = array('totalMoney' =>$MoneyCount,'dingdancode'=>$dingdancode);
		$this->success($result);
	}
	//第三方支付充值获取订单号
	//$_POST['addmoney']=100;
	$addmoney=$_POST['addmoney'];
	if ($addmoney&&$uid) {
		$dingdancode = pay_get_dingdan_code('C');
		$query = $this->db->Query("INSERT INTO `@#_member_addmoney_record` (`uid`, `code`, `money`, `pay_type`, `status`,`time`,`score`,`scookies`) VALUES ('$uid', '$dingdancode', '$addmoney', '','未付款', '','','')");
		$result = array('addmoney' =>$addmoney,'dingdancode'=>$dingdancode);
		$this->success($result);
	}

}
	//从账户余额直接购买商品
	public function buyByAccount()
	{
		$code=$_POST['dingdancode'];
		//$code='A14618143160302056';/Volumes/mac os/usr/local/var/www/controller/apicloud/cart.action.bak.php
		$uid=$_POST['uid'];
		//$uid=5;
		$ifOrder=$this->db->GetList("SELECT `id` FROM `@#_member_go_record` where `status` like '%已付款%' and `code`='$code'");
		$totalAmount = $this->db->GetOne("select sum(moneycount) as totalAmount from `@#_member_go_record` where `code` = '$code' and `uid` ='$uid'");
		$MoneyCount=$totalAmount['totalAmount'];
		if($ifOrder){
		  $this->failed('该订单已经付款');
		}
		$this->payAfter($code,$uid,$MoneyCount);
	}
	
	 /**
     * 支付成功后的一系列操作，这里封装在统一一个函数里
     * @access public
     * @param string $code 订单号
     * @param string $uid 用户id
     * @param string $MoneyCount 总金额
     * @param string $isAccount 是否从账户支付
     * @return success or 异常
     */
	public function payAfter($code,$uid,$MoneyCount)
	{		
		$goods_count_num = $this->db->GetOne("select sum(gonumber) as totalAmount,sum(moneycount) as totalMoney from `@#_member_go_record` where `code` = '$code' and `uid` ='$uid'");
		$goods_count_num=$goods_count_num['totalAmount'];
		$goods_count_money = $goods_count_num['totalMoney'];
		$member=$this->getUserInfo($uid);
		$time=time();
		$pay_type='手机app';
		
    	$sids=$this->db->GetList("SELECT `shopid`,`gonumber`,`moneycount` FROM `@#_member_go_record` where `status` ='未付款,未发货,未完成' and `code`='$code' and `uid` = '$uid'");
    	if ($sids) {
    		$shoplist=$this->getShoplist($sids);
    	}else{
				$this->failed('没有商品');
    	}
		$query_1=true;
		$realcodes_num = 0;
		foreach ($sids as $key => $val) {
			$id=$val['shopid'];
			$ret_data = array();
			pay_get_shop_codes($val['moneycount'],$shoplist[$id],$ret_data);
			$dingdan_query = $ret_data['query'];
			$codes = $ret_data['user_code'];
			$realcodes_num+=count(explode(',', $codes));
//			$this->success(array('codes'=>$codes,'gonumber'=>$val['gonumber']));
			$time=sprintf("%.3f",microtime(true));
			if(isset($shoplist[$id])){
			if($shoplist[$id]['canyurenshu'] >= $shoplist[$id]['zongrenshu'] && $shoplist[$id]['maxqishu'] >= $shoplist[$key]['qishu']){
					$this->db->Query("UPDATE `@#_shoplist` SET `canyurenshu`=`zongrenshu`,`shenyurenshu` = '0' where `id` = '$id'");
					pay_insert_shop($shoplist[$id]);
				}else{

				    $canyurenshu = $shoplist[$id]['canyurenshu'] + $val['gonumber'];
					$shenyurenshu = $shoplist[$id]['shenyurenshu'] - $val['gonumber'];
					$uprenshu = $this->db->Query("UPDATE `@#_shoplist` SET `canyurenshu` = '$canyurenshu',`shenyurenshu` = '$shenyurenshu' WHERE `id`='$id'");
					$up_record=$this->db->Query("UPDATE `@#_member_go_record` SET `status`='已付款,未发货,未完成',`goucode`='$codes',`time`='$time',`pay_type`='$pay_type',`feedBack` = 1 WHERE `code`='$code' and `uid` = '$uid' and `shopid`='$id'");
					if(!$uprenshu && !$up_record)$query_1=false;
				}
		}
	}

	if ($goods_count_money>$realcodes_num) {
				$charge = $goods_count_money - $realcodes_num;
				$goods_count_money=$realcodes_num;
				$MoneyCount=$goods_count_money;
				$up_q3 = $this->db->Query("INSERT INTO `@#_member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('$uid', '1', '账户', '中奖码不足返现', '$charge', '$time')");
			}

		$fufen = System::load_app_config("user_fufen",'','member');
		//添加积分
		$mygoscore = $fufen['f_shoppay']*$MoneyCount;
		$mygoscore_text =  "购买了{$goods_count_num}人次商品";
		$query_add_fufen_1 = $this->db->Query("UPDATE `@#_member` SET `score`= score+'$mygoscore' WHERE (`uid`='$uid')");
		$query_add_fufen_2 = $this->db->Query("INSERT INTO `@#_member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('$uid', '1', '积分', '$mygoscore_text', '$mygoscore', '$time')");
		$query_fufen = ($query_add_fufen_1 && $query_add_fufen_2);
//$query_1
		//添加用户经验
		$jingyan = $member['jingyan'] + $fufen['z_shoppay'];
		pay_go_yongjin($uid,$code);
		$query_jingyan = $this->db->Query("UPDATE `@#_member` SET `jingyan`='$jingyan' WHERE (`uid`='$uid')");	//经验值
		$query_2 = $this->db->Query("INSERT INTO `@#_member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('$uid', '-1', '$pay_type', '购买了商品', '$MoneyCount', '$time')");


		$query_3 = $this->db->Query("UPDATE `@#_caches` SET `value`=`value` + $goods_count_num WHERE `key`='goods_count_num'");

		$up_q2 = $this->db->Query("UPDATE `@#_member` SET `money` = `money`-'$MoneyCount' where (`uid` = '$uid')");
		if($query_fufen&&$up_q2 && $query_jingyan && $query_1 && $query_2 && $query_3){
				$this->db->Autocommit_commit();
				$shoplist2=$this->getShoplist($sids);
				foreach($shoplist2 as $shop):
				if($shop['canyurenshu'] >= $shop['zongrenshu'] && $shop['maxqishu'] >= $shop['qishu']){
						$this->db->Autocommit_start();
						$query_insert = pay_insert_shop($shop,'add');
						if(!$query_insert){
							$this->db->Autocommit_rollback();
						}else{
							$this->db->Autocommit_commit();
						}
						$this->db->Query("UPDATE `@#_shoplist` SET `canyurenshu`=`zongrenshu`,`shenyurenshu` = '0' where `id` = '$shop[id]'");
				}	
				endforeach;
				$this->success('OK');
		}else{
			$this->db->Autocommit_rollback();
			$this->failed('支付异常');
		}

	}

	public function checkResult(){
//		$uid = $_POST['uid'];
//		$token = $this->rsa->decrypt($_POST['token']);
//		$time = $_POST['time'];
//		$trustToken = md5(_getcookie("token").$time);
		//	if($token == $trustToken && $uid) {
		$dingdanCode = $_POST['dingdanCode'];
		if (strpos($dingdanCode, 'A1')===0) {
			$result = $this->db->GetOne("SELECT `feedBack`,`status` FROM `@#_member_go_record` WHERE `code` = '$dingdanCode' ORDER BY `id` DESC");
			if($result){
				if($result['feedBack'] == 1){
					if($result['status'] == '已付款,未发货,未完成'){
						$this->success("OK");
					}else{
						$this->failed("付款失败");
					}
				}else{
					$this->success("NO");
				}
			}
		}else if(strpos($dingdanCode,'C1') ===0){
			$result = $this->db->GetOne("SELECT `feedBack`,`status` FROM `@#_member_addmoney_record` WHERE `code` = '$dingdanCode' ORDER BY `id` DESC");
			if($result){
				if($result['feedBack'] == 1){
					if($result['status'] == '已付款'){
						$this->success("OK");
					}else{
						$this->failed("付款失败");
					}
				}else{
					$this->success("NO");
				}
			}
		}



		//	}else{
		//		$this->failed('无权访问');
		//	}
	}
	
  }

  ?>

